package com.adam.example.aggregation.bucket;

import com.adam.example.TransportClientHolder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;

import java.net.UnknownHostException;

public class TermsAggregationExample {

    public static void main(String[] args) throws UnknownHostException {
        TransportClient transportClient = TransportClientHolder.getInstance().getTransportClient();

        TermsAggregationBuilder termsAggregationBuilder = AggregationBuilders.terms("per_count").field("language");
        SearchResponse searchResponse = transportClient.prepareSearch("test_books")
                        .setSize(0).addAggregation(termsAggregationBuilder).get();
        Terms terms = searchResponse.getAggregations().get("per_count");
        for(Terms.Bucket bucket: terms.getBuckets()) {
            System.out.println(bucket.getKey() + ":" + bucket.getDocCount());
        }

        transportClient.close();
    }

}
